﻿using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Reflection;
using System.IO;
using Financial.Componentes;

namespace Financial.Componentes
{
    #region GridView

    /// <summary>
    /// Componente GridView da aplicação.
    /// </summary>
    public partial class GridView : System.Web.UI.WebControls.GridView
    {

        private const string HOTGRIDVIEW_JS = "Financial.Componentes.Resource.GridView.js";

        //private ArrayList cachedSelectedIndices;

        //Atributo que indica se a grid gerou paginação
        bool temPaginacao = false;

        public Button Botao1 = new Button();
        public Button Botao2 = new Button();
        public Button Botao3 = new Button();
        public Button Botao4 = new Button();
        public Button Botao5 = new Button();
        public Button Botao6 = new Button();
        public int intGrid = 1;
        public event CommandEventHandler Botao1Click;
        public event CommandEventHandler Botao2Click;
        public event CommandEventHandler Botao3Click;
        public event CommandEventHandler Botao4Click;
        public event CommandEventHandler Botao5Click;
        public event CommandEventHandler Botao6Click;

        public event EventHandler CheckBoxClick;

        //Eventhandler 
        public event EventHandler StoreQueryFilter;

        #region Propriedades

        public int TotalRowsCount
        {
            get
            {
                if (this.ViewState["TotalRowsCount"] == null)
                {
                    return 0;
                }
                else
                {
                    return (int)this.ViewState["TotalRowsCount"];
                }
            }
            set
            {
                this.ViewState["TotalRowsCount"] = value;
            }
        }

        internal virtual ArrayList SelectedIndices
        {
            get
            {
                ArrayList cachedSelectedIndices = new ArrayList();
                for (int i = 0; i < Rows.Count; i++)
                {
                    // Retrieve the reference to the checkbox
                    CheckBox lCheckBox = (CheckBox)Rows[i].FindControl(InputCheckBoxField.CHECKBOX_ID);
                    lCheckBox.CssClass = "checkbox";

                    if (lCheckBox == null)
                    {
                        return cachedSelectedIndices;
                    }
                    if (lCheckBox.Checked)
                    {
                        cachedSelectedIndices.Add(i);
                    }
                }
                return cachedSelectedIndices;
            }
        }

        public virtual int[] GetSelectedIndices()
        {
            return (int[])SelectedIndices.ToArray(typeof(int));
        }

        [Category("Behavior")]
        [Description("Se a coluna que possui o checkbox é gerado automáticamente em tempo de execução")]
        [DefaultValue(false)]
        public bool AutoGenerateCheckBoxColumn
        {
            get
            {
                object lObject = ViewState["AutoGenerateCheckBoxColumn"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set { ViewState["AutoGenerateCheckBoxColumn"] = value; }
        }

        [Category("Behavior")]
        [Description("Indica a posição 0-based da coluna checkBox")]
        [DefaultValue(0)]
        public int CheckBoxColumnIndex
        {
            get
            {
                object lObject = ViewState["CheckBoxColumnIndex"];
                if (lObject == null)
                {
                    return 0;
                }
                return (int)lObject;
            }
            set
            {
                ViewState["CheckBoxColumnIndex"] = (value < 0 ? 0 : value);
            }
        }

        [Category("Footer Buttons")]
        [Description("Se o Botao1 é gerado no rodapé")]
        [DefaultValue(false)]
        public bool GenerateBotao1
        {
            get
            {
                object lObject = ViewState["GenerateBotao1"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["GenerateBotao1"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Se o Botao2 é gerado no rodapé")]
        [DefaultValue(false)]
        public bool GenerateBotao2
        {
            get
            {
                object lObject = ViewState["GenerateBotao2"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["GenerateBotao2"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Se o Botao3 é gerado no rodapé")]
        [DefaultValue(false)]
        public bool GenerateBotao3
        {
            get
            {
                object lObject = ViewState["GenerateBotao3"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["GenerateBotao3"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Se o Botao4 é gerado no rodapé")]
        [DefaultValue(false)]
        public bool GenerateBotao4
        {
            get
            {
                object lObject = ViewState["GenerateBotao4"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["GenerateBotao4"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Se o Botao5 é gerado no rodapé")]
        [DefaultValue(false)]
        public bool GenerateBotao5
        {
            get
            {
                object lObject = ViewState["GenerateBotao5"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["GenerateBotao5"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Se o Botao6 é gerado no rodapé")]
        [DefaultValue(false)]
        public bool GenerateBotao6
        {
            get
            {
                object lObject = ViewState["GenerateBotao6"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["GenerateBotao6"] = value;
            }
        }

        //[Category("Footer Buttons")]
        //[Description("Insert button page name")]
        //public string PageBotao1
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageBotao1"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageBotao1"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Update button page name")]
        //public string PageBotao2
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageBotao2"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageBotao2"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Delete button page name")]
        //public string PageBotao3
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageBotao3"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageBotao3"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Print button page name")]
        //public string PageBotao5
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageBotao5"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageBotao5"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Detail button page name")]
        //public string PageBotao4
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageBotao4"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageBotao4"] = value;
        //  }
        //}

        ////Functional Button
        //[Category("Footer Buttons")]
        //[Description("Activate Receber button page name")]
        //public string PageReceberButton
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageReceberButton"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageReceberButton"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Activate Acompanhar button page name")]
        //public string PageBotao6
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageBotao6"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageBotao6"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Activate Transferir button page name")]
        //public string PageTransferirButton
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageTransferirButton"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageTransferirButton"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Activate Descartar / Alienar button page name")]
        //public string PageDescartarAlienarButton
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageDescartarAlienarButton"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageDescartarAlienarButton"] = value;
        //  }
        //}

        //[Category("Footer Buttons")]
        //[Description("Activate Ajustar button page name")]
        //public string PageAjustarButton
        //{
        //  get
        //  {
        //    object lObject = ViewState["PageAjustarButton"];
        //    if (lObject == null)
        //    {
        //      return string.Empty;
        //    }
        //    return (string)lObject;
        //  }
        //  set
        //  {
        //    ViewState["PageAjustarButton"] = value;
        //  }
        //}


        [Category("Footer Buttons")]
        [Description("Nome do botão1")]
        [DefaultValue("btnBotao1")]
        public string NomeBotao1
        {
            get
            {
                object lObject = ViewState["NomeBotao1"];
                if (lObject == null)
                {
                    return string.Empty;
                }
                return (string)lObject;
            }
            set
            {
                ViewState["NomeBotao1"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Nome do botão2")]
        [DefaultValue("btnBotao2")]
        public string NomeBotao2
        {
            get
            {
                object lObject = ViewState["NomeBotao2"];
                if (lObject == null)
                {
                    return string.Empty;
                }
                return (string)lObject;
            }
            set
            {
                ViewState["NomeBotao2"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Nome do botão3")]
        [DefaultValue("btnBotao3")]
        public string NomeBotao3
        {
            get
            {
                object lObject = ViewState["NomeBotao3"];
                if (lObject == null)
                {
                    return string.Empty;
                }
                return (string)lObject;
            }
            set
            {
                ViewState["NomeBotao3"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Nome do botão4")]
        [DefaultValue("btnBotao4")]
        public string NomeBotao4
        {
            get
            {
                object lObject = ViewState["NomeBotao4"];
                if (lObject == null)
                {
                    return string.Empty;
                }
                return (string)lObject;
            }
            set
            {
                ViewState["NomeBotao4"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Nome do botão5")]
        [DefaultValue("btnBotao5")]
        public string NomeBotao5
        {
            get
            {
                object lObject = ViewState["NomeBotao5"];
                if (lObject == null)
                {
                    return string.Empty;
                }
                return (string)lObject;
            }
            set
            {
                ViewState["NomeBotao5"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Nome do botão6")]
        [DefaultValue("btnBotao6")]
        public string NomeBotao6
        {
            get
            {
                object lObject = ViewState["NomeBotao6"];
                if (lObject == null)
                {
                    return string.Empty;
                }
                return (string)lObject;
            }
            set
            {
                ViewState["NomeBotao6"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("Determina se há checkbox no Header")]
        [DefaultValue(false)]
        public bool HeaderCheckBox
        {
            get
            {
                object lObject = ViewState["HeaderCheckBox"];
                if (lObject == null)
                {
                    return false;
                }
                return (bool)lObject;
            }
            set
            {
                ViewState["HeaderCheckBox"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("ToolTip do botão1.")]
        [DefaultValue("Botão1")]
        public String ToolTipBotao1
        {
            get
            {
                object lObject = ViewState["ToolTipBotao1"];
                if (lObject == null)
                {
                    return "Botão1";
                }
                return (string)lObject;
            }
            set
            {
                ViewState["ToolTipBotao1"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("ToolTip do botão2.")]
        [DefaultValue("Botão2")]
        public String ToolTipBotao2
        {
            get
            {
                object lObject = ViewState["ToolTipBotao2"];
                if (lObject == null)
                {
                    return "Botão2";
                }
                return (string)lObject;
            }
            set
            {
                ViewState["ToolTipBotao2"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("ToolTip do botão3.")]
        [DefaultValue("Botão3")]
        public String ToolTipBotao3
        {
            get
            {
                object lObject = ViewState["ToolTipBotao3"];
                if (lObject == null)
                {
                    return "Botão3";
                }
                return (string)lObject;
            }
            set
            {
                ViewState["ToolTipBotao3"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("ToolTip do botão4.")]
        [DefaultValue("Botão4")]
        public String ToolTipBotao4
        {
            get
            {
                object lObject = ViewState["ToolTipBotao4"];
                if (lObject == null)
                {
                    return "Botão4";
                }
                return (string)lObject;
            }
            set
            {
                ViewState["ToolTipBotao4"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("ToolTip do botão5.")]
        [DefaultValue("Botão5")]
        public String ToolTipBotao5
        {
            get
            {
                object lObject = ViewState["ToolTipBotao5"];
                if (lObject == null)
                {
                    return "Botão5";
                }
                return (string)lObject;
            }
            set
            {
                ViewState["ToolTipBotao5"] = value;
            }
        }

        [Category("Footer Buttons")]
        [Description("ToolTip do botão6.")]
        [DefaultValue("Botão6")]
        public String ToolTipBotao6
        {
            get
            {
                object lObject = ViewState["ToolTipBotao6"];
                if (lObject == null)
                {
                    return "Botão6";
                }
                return (string)lObject;
            }
            set
            {
                ViewState["ToolTipBotao6"] = value;
            }
        }


        public DataTable FonteDaPaginacao
        {
            get
            {
                object lObject = ViewState["FonteDaPaginacao"];
                if (lObject == null)
                {
                    return null;
                }
                return (DataTable)lObject;
            }
            set
            {
                ViewState["FonteDaPaginacao"] = value;
            }
        }

        public SortDirection Direcao
        {
            get
            {
                if (ViewState["DIRECAO"] == null)
                {
                    ViewState["DIRECAO"] = SortDirection.Ascending;
                }
                return ((SortDirection)ViewState["DIRECAO"]);
            }
            set
            {
                ViewState["DIRECAO"] = value;
            }
        }





        #endregion

        #region Members overrides

        protected override ICollection CreateColumns(PagedDataSource pDataSource, bool pUseDataSource)
        {
            ICollection lColumnList = base.CreateColumns(pDataSource, pUseDataSource);

            if (!AutoGenerateCheckBoxColumn)
            {
                return lColumnList;
            }
            else
            {
                // Adiciona os checkbox se requeridos
                return AddCheckBoxColumn(lColumnList, HeaderCheckBox);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            this.Page.RegisterRequiresControlState(this);



            base.OnInit(e);

            if (!DesignMode)
            {
                // Criação de uma grid vazia para visualização de entrada da tela
                GridViewEmptyDataTemplate gridEmptyDataTemplate = new GridViewEmptyDataTemplate(this);
                this.EmptyDataTemplate = gridEmptyDataTemplate;
            }

            //Adiciona Paginação
            AllowPaging = true;

            //Adiciona alternação da cor da linha
            this.Caption = this.Caption;
            this.AutoGenerateColumns = false;
            this.CssClass = "grid";
            this.Width = Unit.Percentage(100);
            this.PageIndexChanging += new GridViewPageEventHandler(GridView_PageIndexChanging);

        }

        void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (this.PageIndex >= 0)
            {
                SalvaCheckBox(InputCheckBoxField.CHECKBOX_ID, this);
                this.PageIndex = e.NewPageIndex;
                this.DataSource = this.FonteDaPaginacao;
                this.DataBind();
                RecuperaCheckBox(InputCheckBoxField.CHECKBOX_ID, this);
            }
        }

        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            int lRetorno = base.CreateChildControls(dataSource, dataBinding);
            if (TopPagerRow != null)
            {
                this.TopPagerRow.Visible = true;
            }
            if (this.BottomPagerRow != null)
            {
                this.BottomPagerRow.Visible = true;
            }
            return lRetorno;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Type lType = this.GetType();
            if (!Page.ClientScript.IsClientScriptIncludeRegistered(lType, HOTGRIDVIEW_JS))
            {
                string lUrl = Page.ClientScript.GetWebResourceUrl(lType, HOTGRIDVIEW_JS);
                Page.ClientScript.RegisterClientScriptInclude(lType, HOTGRIDVIEW_JS, lUrl);
            }
            //Alterando o ID dos botões para o informado na propriedade
            Botao1.ID = NomeBotao1;
            Botao2.ID = NomeBotao2;
            Botao3.ID = NomeBotao3;
            Botao4.ID = NomeBotao4;
            Botao5.ID = NomeBotao5;
            Botao6.ID = NomeBotao6;

        }

        protected override void OnPreRender(EventArgs e)
        {

            //Desmarcando o header se tiver alguma linha
            if (TotalRowsCount > 0)
            {
                //  ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DesmarcarHeader", "<script language='JavaScript'> DesCheckHeader('" + String.Format(CHECKBOX_COLUM_HEADER_ID, ClientID) + "');</script>",true);
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "DesmarcarHeader", "<script language='JavaScript'> DesCheckHeader('" + String.Format(CHECKBOX_COLUM_HEADER_ID, ClientID) + "');</script>");
            }

            base.OnPreRender(e);

        }

        protected override void OnRowDataBound(GridViewRowEventArgs e)
        {
            base.OnRowDataBound(e);
            //   e.Row.ID = "Grid_" + intGrid.ToString();
            //  intGrid += 1;

            if (e.Row.RowType.Equals(DataControlRowType.DataRow))
            {
                // Get the appropriate style object for the row
                TableItemStyle style = GetRowStyleFromState(e.Row.RowState);

                // Retrieve the reference to the checkbox
                CheckBox lCheckBox = (CheckBox)e.Row.FindControl(InputCheckBoxField.CHECKBOX_ID);
                if (lCheckBox != null)
                {
                    string lHeaderCheckBoxID = String.Format(CHECKBOX_COLUM_HEADER_ID, ClientID);

                    lCheckBox.Attributes.Add("onClick", "DesCheckHeader('" + String.Format(CHECKBOX_COLUM_HEADER_ID, ClientID) + "')");

                    e.Row.HorizontalAlign = HorizontalAlign.Center;

                    // Update the style of the checkbox if checked
                    if (lCheckBox.Checked)
                    {
                        e.Row.BackColor = SelectedRowStyle.BackColor;
                        e.Row.ForeColor = SelectedRowStyle.ForeColor;
                        e.Row.Font.Bold = SelectedRowStyle.Font.Bold;
                    }
                    else
                    {
                        e.Row.BackColor = style.BackColor;
                        e.Row.ForeColor = style.ForeColor;
                        e.Row.Font.Bold = style.Font.Bold;
                    }
                }
            }
        }

        protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            base.OnRowCreated(e);

            if (e.Row.RowType.Equals(DataControlRowType.Header))
            {
                temPaginacao = false;
            }
        }

        protected override void OnSorting(GridViewSortEventArgs e)
        {
            //      base.OnSorting(e);
            string DIRECAO;
            DataView Dado;
            this.PageIndex = 0;
            if (Direcao == SortDirection.Ascending)
            {
                Direcao = SortDirection.Descending;
                DIRECAO = " DESC";
            }
            else
            {
                Direcao = SortDirection.Ascending;
                DIRECAO = " ASC";
            }
            Dado = this.FonteDaPaginacao.DefaultView;
            Dado.Sort = e.SortExpression + DIRECAO;
            this.DataSource = Dado;
            this.DataBind();

        }

        public void ButtonsHandler(object sender, CommandEventArgs e)
        {
            if (StoreQueryFilter != null)
                StoreQueryFilter.Invoke(sender, e);

            var lStartParametros = new StringBuilder("&");
            var lParametros = new StringBuilder("&");
            String lKey = string.Empty;



            if (((Button)sender).ID == NomeBotao1)
            {
                if (Botao1Click != null)
                    Botao1Click(sender, e);
            }
            else if (((Button)sender).ID == NomeBotao2)
            {
                if (Botao2Click != null)
                    Botao2Click(sender, e);
            }
            else if (((Button)sender).ID == NomeBotao3)
            {
                if (Botao3Click != null)
                    Botao3Click(sender, e);
            }
            else if (((Button)sender).ID == NomeBotao4)
            {
                if (Botao4Click != null)
                    Botao4Click(sender, e);
            }
            else if (((Button)sender).ID == NomeBotao5)
            {
                if (Botao5Click != null)
                    Botao5Click(sender, e);
            }
            else if (((Button)sender).ID == NomeBotao6)
            {
                if (Botao6Click != null)
                    Botao6Click(sender, e);
            }
        }


        /// <summary>
        /// Método InitializePager da grid
        /// </summary>
        /// <param name="row">GridViewRow do Pager</param>
        /// <param name="columnSpan">Quantidade de Colunas para o span</param>
        /// <param name="pagedDataSource">Dados da paginação</param>
        protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
        {
            //Verifica se houve páginas
            if (pagedDataSource.PageCount > 0)
            {
                temPaginacao = true;
                PagerTemplate = new PagerTemplateFinancial(this.PageIndex, this.PageCount, this.TotalRowsCount, this);
            }

            base.InitializePager(row, columnSpan, pagedDataSource);
        }

        #endregion

        #region Métodos
        private void SalvaCheckBox(string pCheckBoxName, Financial.Componentes.GridView pGrid)
        {
            MantemTodosCheckBox(pCheckBoxName, pGrid);
            ArrayList arr = ((ArrayList)ViewState["arr_" + pCheckBoxName]);
            if (arr == null)
            {
                arr = new ArrayList();
            }
            else
            {
                arr.Sort();
            }


            CheckBox ck;
            foreach (GridViewRow item in pGrid.Rows)
            {
                ck = ((CheckBox)item.FindControl(pCheckBoxName));
                if (ck != null)
                {
                    String id = Convert.ToString(pGrid.DataKeys[item.RowIndex].Value);
                    bool achou = arr.Contains(id);
                    if (achou && !ck.Checked)
                    {
                        arr.Remove(id); //Remove do Array
                    }
                    else if (achou == false && ck.Checked)
                    {
                        arr.Add(id); //Adiciona ao Array
                    }
                }
            }
            ViewState["arr_" + pCheckBoxName] = arr;

        }
        private void RecuperaCheckBox(string pCheckBoxName, Financial.Componentes.GridView pGrid)
        {
            MantemTodosCheckBox(pCheckBoxName, pGrid);
            ArrayList arr = ((ArrayList)ViewState["arr_" + pCheckBoxName]);
            if (arr == null)
            {
                arr = new ArrayList();
            }
            else
            {
                arr.Sort();
            }

            CheckBox ck;
            foreach (GridViewRow item in pGrid.Rows)
            {
                ck = ((CheckBox)item.FindControl(pCheckBoxName));
                if (ck != null)
                {
                    String id = Convert.ToString(pGrid.DataKeys[item.RowIndex].Value);

                    if (arr.Contains(id))
                    {
                        ck.Checked = true;
                    }
                }
            }

        }

        private String marcaTodos
        {
            get
            {
                String marcaTodos = ((Financial.Componentes.PagerTemplateFinancial)(this.PagerTemplate)).hfCheckBox.Value;
                if (marcaTodos != "")
                    ViewState["_marcaTodos"] = marcaTodos;
                else
                    marcaTodos = (String)ViewState["_marcaTodos"];

                return marcaTodos;
            }
        }

        private bool? preencheuTodos
        {
            get { return (bool?)ViewState["preencheuTodos"]; }
            set { ViewState["preencheuTodos"] = value; }
        }

        private void MantemTodosCheckBox(string pCheckBoxName, Financial.Componentes.GridView pGrid)
        {
            ArrayList arr = ((ArrayList)ViewState["arr_" + pCheckBoxName]);
            if (arr == null)
                arr = new ArrayList();
            else
                arr.Sort();

            //object checkBoxHeader = Page.Request[String.Format(CHECKBOX_COLUM_HEADER_ID, ClientID)];
            if (marcaTodos == "True")
            {
                if (preencheuTodos != true)
                {
                    preencheuTodos = true;
                    foreach (DataRow row in FonteDaPaginacao.Rows)
                    {
                        if (!arr.Contains(Convert.ToString(row[this.DataKeyNames[0]])))
                            arr.Add(Convert.ToString(row[this.DataKeyNames[0]]));
                    }
                }
            }
            else
            {
                if (preencheuTodos != null)
                {
                    if ((bool)preencheuTodos)
                    {
                        arr = null;
                        preencheuTodos = false;
                    }
                }
            }

            ViewState["arr_" + pCheckBoxName] = arr;

        }

        public DataTable SelecionaRegistrosMarcados()
        {
            //String hfCheckBoxClientID = String.Format("{0}_ctl" + String.Format("{0:D2}", this.Rows.Count + 3) + HIDDENFIELD_ID, ClientID);

            SalvaCheckBox(InputCheckBoxField.CHECKBOX_ID, this);
            ArrayList arr = ((ArrayList)ViewState["arr_" + InputCheckBoxField.CHECKBOX_ID]);

            DataTable dt = new DataTable();
            dt = FonteDaPaginacao.Copy();
            Int32 count = 0;

            foreach (DataRow row in FonteDaPaginacao.Rows)
            {
                if (!arr.Contains(Convert.ToString(row[this.DataKeyNames[0]])))
                {
                    dt.Rows.RemoveAt(count);
                    count--;
                }
                count++;
            }

            return dt;
        }

        #endregion

    }

    #endregion

    #region Template para Grid Vazia

    public class GridViewEmptyDataTemplate : ITemplate
    {
        #region Propriedades
        private const string cteHeaderButtonDetail = "&nbsp;Visualizar&nbsp;";
        private const string cteHeaderButtonEdit = "&nbsp;Editar&nbsp;";
        private const string cteHeaderButtonDelete = "&nbsp;Excluir&nbsp;";
        #endregion

        #region ITemplate Members

        private GridView _owner;
        public GridViewEmptyDataTemplate(Financial.Componentes.GridView owner)
        {
            _owner = owner;
        }

        protected Financial.Componentes.GridView GetGridView()
        {
            return _owner;
        }

        public void InstantiateIn(Control container)
        {
            ((TableCell)container).ColumnSpan = 0;

            int columnSpanColumns = 0;

            // criando a table interna ao table do render do empty.
            Table tableEmptyTemplate = new Table();
            tableEmptyTemplate.Width = new Unit("100%");
            tableEmptyTemplate.CellPadding = 0;
            tableEmptyTemplate.CellSpacing = 0;
            //tableEmptyTemplate.Style.Add("border", "1px solid #E1E1E1");

            #region "ColumnsEmpty"
            // criando a linha (TR) das colunas do GridView.
            TableHeaderRow headerTableRow = new TableHeaderRow();

            DataControlFieldCollection dataControlFieldCollection = GetGridView().Columns;
            headerTableRow.CssClass = GetGridView().HeaderStyle.CssClass;
            headerTableRow.Style.Add("height", "23px");




            foreach (DataControlField dataControlField in dataControlFieldCollection)
            {
                if (dataControlField.Visible && !dataControlField.ToString().Equals(cteHeaderButtonDetail)
                  && !dataControlField.ToString().Equals(cteHeaderButtonDelete)
                  && !dataControlField.ToString().Equals(cteHeaderButtonEdit))
                {
                    columnSpanColumns++;

                    TableHeaderCell tableCellColumn = new TableHeaderCell();

                    //Style styleCellColumn = new Style();
                    //dataControlField.HeaderStyle.CopyFrom(styleCellColumn);

                    if (this.GetGridView().Columns.Count > 2)
                    {
                        if (dataControlField.HeaderText != string.Empty)
                            tableCellColumn.Text = dataControlField.HeaderText;
                        else
                            tableCellColumn.Text = "&nbsp;";

                        if (dataControlField.HeaderStyle.Width != null)
                            tableCellColumn.Width = dataControlField.HeaderStyle.Width;
                        else
                            tableCellColumn.Width = dataControlField.ItemStyle.Width;

                        tableCellColumn.HorizontalAlign = dataControlField.ItemStyle.HorizontalAlign;

                        // adicionando a celula ao headerTableRow
                        headerTableRow.Cells.Add(tableCellColumn);
                    }
                    else
                    {
                        if (!dataControlField.HeaderText.Equals(" "))
                        {
                            if (dataControlField.HeaderText != string.Empty)
                                tableCellColumn.Text = dataControlField.HeaderText;
                            else
                                tableCellColumn.Text = "&nbsp;";

                            if (dataControlField.HeaderStyle.Width != null)
                                tableCellColumn.Width = dataControlField.HeaderStyle.Width;
                            else
                                tableCellColumn.Width = dataControlField.ItemStyle.Width;

                            tableCellColumn.HorizontalAlign = dataControlField.ItemStyle.HorizontalAlign;


                            // adicionando a celula ao headerTableRow
                            headerTableRow.Cells.Add(tableCellColumn);
                        }
                    }

                }
            }

            // adicionando a linha (tr) do header ao table.
            tableEmptyTemplate.Rows.Add(headerTableRow);

            #endregion

            TableRow tableRow = new TableRow();
            TableCell tableCell = new TableCell();
            tableCell.HorizontalAlign = HorizontalAlign.Center;
            tableCell.ID = "TdVazia";
            tableCell.ColumnSpan = columnSpanColumns;
            tableCell.CssClass = GetGridView().AlternatingRowStyle.CssClass;
            tableCell.Text = "Não foi encontrado registro para o filtro solicitado.";
            tableCell.Style.Add("Font-Size", "12pt");
            tableCell.Style.Add("height", "23px");
            tableCell.Style.Add("cellSpacing", "0");
            // tableCell.Style.Add("border", "1px solid #E1E1E1");


            tableRow.Cells.Add(tableCell);

            // adicionando a linha (tr) do registro vazio ao table.
            tableEmptyTemplate.Rows.Add(tableRow);

            #region "FooterEmpty"

            TableRow footerTableRow = new TableRow();

            TableCell footerTableCell = new TableCell();
            footerTableCell.HorizontalAlign = HorizontalAlign.Right;
            //footerTableCell.Text = "0 Registro(s)";
            footerTableCell.ColumnSpan = columnSpanColumns;
            footerTableCell.CssClass = GetGridView().FooterStyle.CssClass;

            Button lButton = null;

            //Botões funcionais

            if (_owner.GenerateBotao1)
            {
                lButton = _owner.addButton(_owner.Botao1, _owner.ToolTipBotao1, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao1;
                lButton.Text = _owner.NomeBotao1;
                lButton.CssClass = "botao01";
                footerTableCell.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao2)
            {
                lButton = _owner.addButton(_owner.Botao2, _owner.ToolTipBotao2, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao2;
                lButton.Text = _owner.NomeBotao2;
                lButton.CssClass = "botao01";
                footerTableCell.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao3)
            {
                lButton = _owner.addButton(_owner.Botao3, _owner.ToolTipBotao3, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao3;
                lButton.Text = _owner.NomeBotao3;
                lButton.CssClass = "botao01";
                footerTableCell.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao4)
            {
                lButton = _owner.addButton(_owner.Botao4, _owner.ToolTipBotao4, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao4;
                lButton.Text = _owner.NomeBotao4;
                lButton.CssClass = "botao01";
                footerTableCell.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao5)
            {
                lButton = _owner.addButton(_owner.Botao5, _owner.ToolTipBotao5, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao5;
                lButton.Text = _owner.NomeBotao5;
                lButton.CssClass = "botao01";
                footerTableCell.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao6)
            {
                lButton = _owner.addButton(_owner.Botao6, _owner.ToolTipBotao6, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao6;
                lButton.Text = _owner.NomeBotao6;
                lButton.CssClass = "botao01";
                footerTableCell.Controls.Add(lButton);
            }

            footerTableRow.Cells.Add(footerTableCell);

            // adicionando a linha (tr) do registro vazio ao table.
            tableEmptyTemplate.Rows.Add(footerTableRow);

            #endregion

            container.Controls.Add(tableEmptyTemplate);
        }

        #endregion
    }

    #endregion

    #region Template para Navegador

    public class PagerTemplateFinancial : ITemplate
    {

        int _pageIndex;

        int _pageCount;

        int _rowCount;
        public HiddenField hfCheckBox;
        Financial.Componentes.GridView _owner;

        int _pageNumber
        {
            get
            {
                return _pageIndex + 1;
            }
            set
            {
                _pageIndex = value - 1;
            }
        }

        private int pageIndex(int pageNumber)
        {
            return pageNumber - 1;
        }

        public PagerTemplateFinancial(int pageIndex, int pageCount, int rowCount, Financial.Componentes.GridView owner)
        {
            _pageIndex = pageIndex;
            _pageCount = pageCount;
            _rowCount = rowCount;
            _owner = owner;
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {

            Literal controle = new Literal();
            controle.Text = @"<table class='grid_rodape' border='0' align='left' cellpadding='0' cellspacing='0'>
                            <tr>".Replace('\'', '"');
            container.Controls.Add(controle);

            Label meuLabel = new Label();

            controle = new Literal();
            controle.Text = @"<td align='center' style='width: 22px' valign='middle'>".Replace('\'', '"');
            container.Controls.Add(controle);

            ImageButton meuImageButton = new ImageButton();
            meuImageButton.ID = "ibtnSetaInicio";
            meuImageButton.CommandName = "Page";
            meuImageButton.CommandArgument = "First";
            meuImageButton.ImageUrl = "~/images/NavHome.gif";
            meuImageButton.Style.Add(HtmlTextWriterStyle.BackgroundColor, "transparent");


            if (_pageNumber == 1)
            {
                meuImageButton.Enabled = false;
            }
            container.Controls.Add(meuImageButton);

            controle = new Literal();
            controle.Text = @"</td><td align='center' style='width: 22px' valign='middle'>".Replace('\'', '"');
            container.Controls.Add(controle);

            meuImageButton = new ImageButton();
            meuImageButton.ID = "ibtnSetaAtras";
            meuImageButton.CommandName = "Page";
            meuImageButton.CommandArgument = "Prev";
            meuImageButton.ImageUrl = "~/images/NavPrev.gif";
            meuImageButton.Style.Add(HtmlTextWriterStyle.BackgroundColor, "transparent");

            if (_pageNumber == 1)
            {
                meuImageButton.Enabled = false;
            }
            container.Controls.Add(meuImageButton);


            controle = new Literal();
            controle.Text = @"</td><td style='height: 10; width: 100'><div align='center' style='width: 100px'>".Replace('\'', '"');
            container.Controls.Add(controle);

            meuLabel = new Label();
            meuLabel.ID = "lblPagAtual";
            meuLabel.Text = "Página" + _pageNumber.ToString() + "de ".ToString();
            container.Controls.Add(meuLabel);

            meuLabel = new Label();
            meuLabel.ID = "lblPagTotal";
            meuLabel.Text = _pageCount.ToString();
            container.Controls.Add(meuLabel);

            controle = new Literal();
            controle.Text = @"</div>
               </td><td align='center' style='width: 22px' valign='middle'>".Replace('\'', '"');
            container.Controls.Add(controle);


            meuImageButton = new ImageButton();
            meuImageButton.ID = "ibtnSetaFrente";
            meuImageButton.CommandName = "Page";
            meuImageButton.CommandArgument = "Next";
            meuImageButton.ImageUrl = "~/images/NavNext.gif";
            meuImageButton.Style.Add(HtmlTextWriterStyle.BackgroundColor, "transparent");
            if (_pageCount < 2)
            {
                meuImageButton.Enabled = false;
            }
            container.Controls.Add(meuImageButton);

            controle = new Literal();
            controle.Text = @"</td><td align='center' style='width: 22px' valign='middle'>".Replace('\'', '"');
            container.Controls.Add(controle);

            meuImageButton = new ImageButton();
            meuImageButton.ID = "ibtnSetaFim";
            meuImageButton.CommandName = "Page";
            meuImageButton.CommandArgument = "Last";
            meuImageButton.ImageUrl = "~/images/NavEnd.gif";
            meuImageButton.Style.Add(HtmlTextWriterStyle.BackgroundColor, "transparent");
            if (_pageCount < 2)
            {
                meuImageButton.Enabled = false;
            }
            container.Controls.Add(meuImageButton);

            controle = new Literal();
            controle.Text = @"</td>";
            container.Controls.Add(controle);


            controle = new Literal();
            controle.Text = @"<td style='width: 100%'>";
            container.Controls.Add(controle);

            Button lButton = null;

            controle = new Literal();
            controle.Text = @" <table border='0' align='right' width='100%' cellpadding='0' cellspacing='0'>
        <tr>".Replace('\'', '"');
            container.Controls.Add(controle);

            controle = new Literal();
            controle.Text = @"<td style='height: 80%' align='right' bgcolor='#FFFFFF'>".Replace('\'', '"');
            container.Controls.Add(controle);
            //Botões funcionais
            if (_owner.GenerateBotao1)
            {
                lButton = _owner.addButton(_owner.Botao1, _owner.ToolTipBotao1, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao1;
                lButton.Text = _owner.NomeBotao1;
                lButton.CssClass = "botao01";
                container.Controls.Add(lButton);
            }
            if (_owner.GenerateBotao2)
            {
                lButton = _owner.addButton(_owner.Botao2, _owner.ToolTipBotao2, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao2;
                lButton.Text = _owner.NomeBotao2;
                lButton.CssClass = "botao01";
                container.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao3)
            {
                lButton = _owner.addButton(_owner.Botao3, _owner.ToolTipBotao3, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao3;
                lButton.Text = _owner.NomeBotao3;
                lButton.CssClass = "botao01";
                container.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao4)
            {
                lButton = _owner.addButton(_owner.Botao4, _owner.ToolTipBotao4, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao4;
                lButton.Text = _owner.NomeBotao4;
                lButton.CssClass = "botao01";
                container.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao5)
            {
                lButton = _owner.addButton(_owner.Botao5, _owner.ToolTipBotao5, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao5;
                lButton.Text = _owner.NomeBotao5;
                lButton.CssClass = "botao01";
                container.Controls.Add(lButton);
            }

            if (_owner.GenerateBotao6)
            {
                lButton = _owner.addButton(_owner.Botao6, _owner.ToolTipBotao6, _owner.ButtonsHandler);
                lButton.CausesValidation = true;
                lButton.ValidationGroup = _owner.NomeBotao6;
                lButton.Text = _owner.NomeBotao6;
                lButton.CssClass = "botao01";
                container.Controls.Add(lButton);
            }

            hfCheckBox = new HiddenField();
            hfCheckBox.ID = "GridView_HiddenCheckBox";
            container.Controls.Add(hfCheckBox);

            controle = new Literal();
            controle.Text = @"</td>".Replace('\'', '"');
            container.Controls.Add(controle);

            controle = new Literal();
            controle.Text = @"</tr></table>".Replace('\'', '"');
            container.Controls.Add(controle);

            controle = new Literal();
            controle.Text = @"</td>";
            container.Controls.Add(controle);

            controle = new Literal();
            controle.Text = @"</tr></table>";
            container.Controls.Add(controle);

        }


        #endregion
    }

    #endregion

    #region Helpers
    public partial class GridView : System.Web.UI.WebControls.GridView
    {
        #region Constants

        private const string CHECKBOX_COLUM_HEADER_TEMPLATE = "<input type='checkbox' class='checkbox' hidefocus='true' id='{0}' name='{0}' {1} onclick='CheckAll(this)'>&nbsp;";
        private const string CHECKBOX_COLUM_HEADER_ID = "{0}_HeaderButton";
        private const string HIDDENFIELD_ID = "_GridView_HiddenCheckBox";

        #endregion

        //private DataGridButtons _FooterButtons = new DataGridButtons();
        private System.Collections.ArrayList buttons = new System.Collections.ArrayList();


        // METHOD:: add a brand new checkbox column
        protected virtual ArrayList AddCheckBoxColumn(ICollection pColumnList, bool pCheckInHeader)
        {
            // Get a new container of type ArrayList that contains the given collection. 
            // This is required because ICollection doesn't include Add methods
            // For guidelines on when to use ICollection vs IList see Cwalina's blog
            ArrayList lList = new ArrayList(pColumnList);
            InputCheckBoxField lField = new InputCheckBoxField();


            // Determine the check state for the header checkbox

            if (pCheckInHeader)
            {
                string lShouldCheck = "";
                string lCheckBoxID = String.Format(CHECKBOX_COLUM_HEADER_ID, ClientID);
                if (!DesignMode)
                {
                    object lCheckBoxIDObject = Page.Request[lCheckBoxID];
                    if (lCheckBoxIDObject != null)
                    {
                        lShouldCheck = "checked=\"checked\"";
                    }
                }




                // Create a new custom CheckBoxField object 

                lField.HeaderText = String.Format(CHECKBOX_COLUM_HEADER_TEMPLATE, lCheckBoxID, lShouldCheck);
                //lField.HeaderStyle.BorderColor = Color.White;
                // lField.HeaderStyle.BorderWidth = new Unit(0);
                lField.HeaderStyle.Width = System.Web.UI.WebControls.Unit.Percentage(1);
                lField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            }

            lField.ReadOnly = true;
            //lField.ItemStyle.Width = System.Web.UI.WebControls.Unit.Pixel(27);
            //lField.ItemStyle.BorderWidth = new Unit(0);
            lField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;


            // Insert the checkbox field into the list at the specified position
            // if (CheckBoxColumnIndex > lList.Count)
            //  {
            // If the desired position exceeds the number of columns 
            // add the checkbox field to the right. Note that this check
            // can only be made here because only now we know exactly HOW 
            // MANY columns we're going to have. Checking Columns.Count in the 
            // property setter doesn't work if columns are auto-generated
            lList.Add(lField);
            //    CheckBoxColumnIndex = lList.Count - 1;
            //  }
            // else
            //     lList.Insert(CheckBoxColumnIndex, lField);

            // Return the new list
            return lList;
        }


        // METHOD:: retrieve the style object based on the row state
        protected virtual TableItemStyle GetRowStyleFromState(DataControlRowState pState)
        {
            switch (pState)
            {
                case DataControlRowState.Alternate:
                    return AlternatingRowStyle;
                case DataControlRowState.Edit:
                    return EditRowStyle;
                case DataControlRowState.Selected:
                    return SelectedRowStyle;
                default:
                    return RowStyle;

                // DataControlRowState.Insert is not relevant here
            }
        }

        public Button addButton(Button pBtn, string pToolTip, CommandEventHandler pCommand)
        {
            pBtn.ToolTip = pToolTip;
            if (pCommand != null)
                pBtn.Command += pCommand;

            return pBtn;
        }


        private bool FooterButtonExists(string pId)
        {

            bool lExisteRetorno = false;

            for (int lIndex = 0; lIndex < buttons.Count; lIndex++)
            {
                if (((ImageButton)buttons[lIndex]).ID == pId)
                {
                    lExisteRetorno = true;
                }
            }
            return lExisteRetorno;
        }

        protected override void PerformDataBinding(System.Collections.IEnumerable data)
        {
            if (!DesignMode)
            {
                if (data is System.Data.DataView)
                {
                    //       this.TotalRowsCount = ((System.Data.DataView)data).Count;
                }
                else
                {
                    //         this.TotalRowsCount = 0;
                }
            }
            else
            {
                //    this.TotalRowsCount = 0;
            }
            base.PerformDataBinding(data);
        }
    }
    #endregion

}
